const { Service } = require('egg');
class UserService extends Service {
  // 新增
  async create(params) {
    try {
      const { ctx } = this;
      const result = await ctx.model.User.create(params);
      return result;
    } catch (error) {
      return null;
    }
  }
  // 分页
  async page({ pageIndex, pageSize }) {
    try {
      const { ctx, app } = this;
      const result = await ctx.model.User.findAndCountAll({
        order: [['created_at', 'DESC']],
        limit: parseInt(pageSize), // 每页多少条
        offset: parseInt(pageSize) * (parseInt(pageIndex) - 1), // 跳过多少条
        where:{ flag:1}
      });
      return result;
    } catch (error) {
      return null;
    }
  }
  //  获取
  async info(payload) {
    try {
      const { ctx } = this;
      const result = await ctx.model.User.findOne({
        where: {
          ...payload,
          flag:1
        },
      });
      return result;
    } catch (error) {
      return null;
    }
  }
  // 修改
  async edit(data) {
    let { userId } = data;
    try {
      const { ctx } = this;
      const result = await ctx.model.User.update(
        { ...data },
        {
          where: {
            userId,
          },
        }
      );
      return result;
    } catch (error) {
      return null;
    }
  }
  // 删除
  async del(id) {
    try {
      const { ctx } = this;
      const result = await ctx.model.User.update(
        { flag: 0 },
        {
          where: {
            user_id: id,
          },
        }
      );
      return result;
    } catch (error) {
      return null;
    }
  }
  // 登录
  async login({ email }) {
    try {
      const { ctx } = this;
      const result = await ctx.model.User.findOne({
        where: { email , flag:1},
      });
      return result;
    } catch (error) {
      return null;
    }
  }
  // 密码
  async pwd({ email, password }) {
    try {
      const { ctx } = this;
      const result = await ctx.model.User.update(
        { password },
        {
          where: {
            email,
            flag:1
          },
        }
      );
      return result;
    } catch (error) {
      return null;
    }
  }
}
module.exports = UserService;
